//
//  HomeViewController.swift
//  SwiftPanda
//
//  Created by 余意 on 2017/2/28.
//  Copyright © 2017年 余意. All rights reserved.
//

import UIKit
import WebKit
import Alamofire
import SwiftyJSON

class HomeViewController: UIViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler{
    
    lazy var homeWKWebView : WKWebView = {
        
        let configuretion = WKWebViewConfiguration()
        configuretion.userContentController.add(self, name: "getToken")
        configuretion.userContentController.add(self, name: "goAuto")
        configuretion.userContentController.add(self, name: "goMyCustomers")
        configuretion.userContentController.add(self, name: "goGold")
        configuretion.userContentController.add(self, name: "goInvite")
        configuretion.userContentController.add(self, name: "goMyOrders")
        configuretion.userContentController.add(self, name: "goProduct")
        configuretion.userContentController.add(self, name: "pandaAppPay")
        configuretion.userContentController.add(self, name: "pandaAppLogout")
        configuretion.userContentController.add(self, name: "downLoadUrl")
        configuretion.userContentController.add(self, name: "pandaAppShare")
        configuretion.userContentController.add(self, name: "callPhone")
        configuretion.userContentController.add(self, name: "endEditing")
        configuretion.userContentController.add(self, name: "navChange")
        configuretion.userContentController.add(self, name: "goFirstTeam")
        configuretion.userContentController.add(self, name: "pandaAppImgShare")
        configuretion.userContentController.add(self, name: "pandaMap")
        configuretion.userContentController.add(self, name: "getLotteryRule")
        
        configuretion.preferences = WKPreferences()
        configuretion.preferences.minimumFontSize = 10
        configuretion.preferences.javaScriptEnabled = true
        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = false
        configuretion.processPool = WKProcessPool()
        
        let webView = WKWebView(frame:self.view.bounds,configuration:configuretion)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        return webView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        let backBtn = UIButton()
        backBtn.addTarget(self, action: #selector(backBtnClick(_:)), for: .touchUpInside)
        backBtn.backgroundColor = UIColor.white
        backBtn.frame = CGRect(x:0,y:0,width:44,height:30)
        let leftItem = UIBarButtonItem(customView:backBtn)
        self.navigationItem.leftBarButtonItem = leftItem
        
        
        let rightBtn = UIButton()
        rightBtn.setTitle("增员", for: .normal)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        rightBtn.setTitleColor(UIColor.white, for: .normal)
        rightBtn.addTarget(self, action: #selector(rightBtnClick(_:)), for: .touchUpInside)
        rightBtn.frame = CGRect(x:40,y:0,width:44,height:30)
        let rightItem = UIBarButtonItem(customView:rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
//        let PLVC = PasswordLoginViewController()
//        let NavPLVC = PandaNavigationController(rootViewController:PLVC)
//        self.navigationController?.present(NavPLVC,animated: true,completion: nil)
        
        self.view.addSubview(homeWKWebView)
        
        getServerVersion()

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK:- WKNavigationDelegate
    //页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    }
    
    //webView开始返回的时候
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    }
    
    //webView加载完成的时候
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
    
    //webView加载失败的时候调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
    }
    
    
    //MARK:- WKUIDelegate
    //创建一个新的webView
//    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
//        
//    }
    
    //界面弹出确认框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let ac = UIAlertController(title: webView.title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        ac.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:
            { (ac) -> Void in
                completionHandler(true)  //按确定的时候传true
        }))
        
        ac.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:
            { (ac) -> Void in
                completionHandler(false)  //取消传false
        }))
        
        self.present(ac, animated: true, completion: nil)
    }
    
    //界面弹出警告框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let ac = UIAlertController(title: webView.title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        ac.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: { (a) -> Void in
            completionHandler()
        }))
        
        self.present(ac, animated: true, completion: nil)
    }
    
    //界面弹出输入框
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let ac = UIAlertController(title: prompt, message: "", preferredStyle: UIAlertControllerStyle.alert)
        ac.addTextField { (tf) in
            tf.text = defaultText!
        }
        let action = UIAlertAction(title:"完成", style:.default, handler: {
            (UIAlertAction) -> Void in
            let _ = (ac.textFields?.first)! as UITextField
        })
        
        ac.addAction(action)
        self.present(ac, animated: true, completion: nil)
    }
    
    //MARK:- WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("JS调用了 \(message.name)方法 ，传回参数\(message.body)")
    }
    
    
    
    //MARK: - response event
    func backBtnClick(_ sender :UIButton)
    {
        print("btn Clicked")
        print("\(sender)")
    }
    
    func rightBtnClick(_ sender: UIButton)
    {
        print("RightBtn Clicked")
    }
    
    //MARK:- Private Class
    func getServerVersion() {
        let urlString = "http://t.99bx.cn/version.json"
    
        
        Alamofire.request(urlString).responseString { (response) in
            
            var versionCode : String = "1.0.0"
            switch response.result {
            case .success:
                
                if let result = response.result.value {
                    let data = response.result.value?.data(using: .utf8)
                    let jsonDic = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:String]
                    print(jsonDic)
                }
                
            case .failure(let error):
                print(error)
            }
        }
    }

}
